// 初始化地图
const map = L.map('map').setView([30, 0], 2);

// 添加地图图层
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// 地震数据URL (最近24小时)
const earthquakeUrl = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';

// 创建粒子背景效果
function createParticles() {
    const particlesContainer = document.getElementById('particles');
    const particleCount = 50;
    
    for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        particle.classList.add('particle');
        
        // 随机大小
        const size = Math.random() * 10 + 2;
        particle.style.width = `${size}px`;
        particle.style.height = `${size}px`;
        
        // 随机位置
        particle.style.left = `${Math.random() * 100}%`;
        particle.style.top = `${Math.random() * 100}%`;
        
        // 随机颜色
        const colors = [
            'rgba(52, 152, 219, 0.6)',
            'rgba(46, 204, 113, 0.6)',
            'rgba(231, 76, 60, 0.6)',
            'rgba(155, 89, 182, 0.6)'
        ];
        particle.style.background = colors[Math.floor(Math.random() * colors.length)];
        
        // 随机动画延迟和持续时间
        const delay = Math.random() * 15;
        const duration = 15 + Math.random() * 10;
        particle.style.animationDelay = `${delay}s`;
        particle.style.animationDuration = `${duration}s`;
        
        particlesContainer.appendChild(particle);
    }
}

// 震级颜色映射
function getMarkerColor(magnitude) {
    return magnitude > 7 ? '#800026' :
           magnitude > 6 ? '#BD0026' :
           magnitude > 5 ? '#E31A1C' :
           magnitude > 4 ? '#FC4E2A' :
           magnitude > 3 ? '#FD8D3C' :
           magnitude > 2 ? '#FEB24C' :
           magnitude > 1 ? '#FED976' :
                          '#FFEDA0';
}

// 根据震级确定标记大小
function getMarkerSize(magnitude) {
    return Math.max(magnitude * 4, 8);
}

// 格式化时间
function formatTime(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        timeZoneName: 'short'
    });
}

// 格式化时间为相对时间
function formatRelativeTime(timestamp) {
    const now = new Date().getTime();
    const diff = now - timestamp;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    
    if (days > 0) {
        return `${days}天前`;
    } else if (hours > 0) {
        return `${hours}小时前`;
    } else {
        return `${minutes}分钟前`;
    }
}

// 创建自定义标记
function createEarthquakeMarker(feature, latlng) {
    const magnitude = feature.properties.mag;
    const place = feature.properties.place;
    const time = feature.properties.time;
    
    return L.circleMarker(latlng, {
        radius: getMarkerSize(magnitude),
        fillColor: getMarkerColor(magnitude),
        color: "#000",
        weight: 1,
        opacity: 1,
        fillOpacity: 0.8,
        className: 'earthquake-marker'
    }).bindPopup(`
        <div class="magnitude-popup">
            <div class="magnitude-info">
                <h3>地震详情</h3>
                <p class="magnitude">震级: ${magnitude.toFixed(1)}</p>
                <p class="place">${place}</p>
                <p class="time">${formatTime(time)}</p>
                <p>深度: ${feature.geometry.coordinates[2]} km</p>
                <p>发生时间: ${formatRelativeTime(time)}</p>
            </div>
        </div>
    `).on('click', function() {
        showEarthquakeDetails(feature);
    });
}

// 显示地震详情
function showEarthquakeDetails(feature) {
    const magnitude = feature.properties.mag;
    const place = feature.properties.place;
    const time = feature.properties.time;
    const tsunami = feature.properties.tsunami ? '是' : '否';
    const felt = feature.properties.felt || '无报告';
    const significance = feature.properties.sig || 'N/A';
    
    document.getElementById('earthquake-details').innerHTML = `
        <div class="magnitude-info">
            <h3>${place}</h3>
            <p class="magnitude">震级: <strong>${magnitude.toFixed(1)}</strong></p>
            <p><span>时间:</span> <span>${formatTime(time)}</span></p>
            <p><span>相对时间:</span> <span>${formatRelativeTime(time)}</span></p>
            <p><span>深度:</span> <span>${feature.geometry.coordinates[2]} km</span></p>
            <p><span>海啸预警:</span> <span>${tsunami}</span></p>
            <p><span>感知报告:</span> <span>${felt}</span></p>
            <p><span>重要性:</span> <span>${significance}/1000</span></p>
            <p><span>经度:</span> <span>${feature.geometry.coordinates[1].toFixed(4)}</span></p>
            <p><span>纬度:</span> <span>${feature.geometry.coordinates[0].toFixed(4)}</span></p>
        </div>
    `;
}

// 更新统计面板
function updateStatsPanel(stats) {
    const statsPanel = document.getElementById('stats-panel');
    statsPanel.innerHTML = `
        <div class="stat-card">
            <h3>地震总数</h3>
            <div class="value">${stats.total}</div>
        </div>
        <div class="stat-card">
            <h3>最大震级</h3>
            <div class="value">${stats.maxMagnitude.toFixed(1)}</div>
        </div>
        <div class="stat-card">
            <h3>平均震级</h3>
            <div class="value">${stats.avgMagnitude.toFixed(1)}</div>
        </div>
        <div class="stat-card">
            <h3>最近地震</h3>
            <div class="value">${stats.mostRecent}</div>
        </div>
    `;
}

// 计算统计数据
function calculateStats(features) {
    if (features.length === 0) {
        return {
            total: 0,
            maxMagnitude: 0,
            avgMagnitude: 0,
            mostRecent: 'N/A'
        };
    }
    
    const magnitudes = features.map(f => f.properties.mag);
    const maxMagnitude = Math.max(...magnitudes);
    const avgMagnitude = magnitudes.reduce((a, b) => a + b, 0) / magnitudes.length;
    
    // 找到最近的地震
    const mostRecentFeature = features.reduce((latest, current) => {
        return current.properties.time > latest.properties.time ? current : latest;
    });
    const mostRecent = formatRelativeTime(mostRecentFeature.properties.time);
    
    return {
        total: features.length,
        maxMagnitude: maxMagnitude,
        avgMagnitude: avgMagnitude,
        mostRecent: mostRecent
    };
}

// 添加图例
function addLegend() {
    const legend = L.control({ position: 'bottomright' });
    
    legend.onAdd = function() {
        const div = L.DomUtil.create('div', 'legend');
        div.innerHTML = `
            <h4>震级图例</h4>
            <div class="legend-item">
                <span class="legend-color" style="background: #800026"></span>
                <span class="legend-label">7+ 级</span>
            </div>
            <div class="legend-item">
                <span class="legend-color" style="background: #BD0026"></span>
                <span class="legend-label">6-7 级</span>
            </div>
            <div class="legend-item">
                <span class="legend-color" style="background: #E31A1C"></span>
                <span class="legend-label">5-6 级</span>
            </div>
            <div class="legend-item">
                <span class="legend-color" style="background: #FC4E2A"></span>
                <span class="legend-label">4-5 级</span>
            </div>
            <div class="legend-item">
                <span class="legend-color" style="background: #FD8D3C"></span>
                <span class="legend-label">3-4 级</span>
            </div>
            <div class="legend-item">
                <span class="legend-color" style="background: #FEB24C"></span>
                <span class="legend-label">2-3 级</span>
            </div>
            <div class="legend-item">
                <span class="legend-color" style="background: #FFEDA0"></span>
                <span class="legend-label">0-2 级</span>
            </div>
        `;
        return div;
    };
    
    legend.addTo(map);
}

// 获取地震数据
async function fetchEarthquakeData() {
    try {
        document.getElementById('earthquake-details').innerHTML = '<p class="loading">正在加载地震数据...</p>';
        
        const response = await fetch(earthquakeUrl);
        if (!response.ok) {
            throw new Error('数据加载失败');
        }
        
        const data = await response.json();
        
        // 计算并显示统计数据
        const stats = calculateStats(data.features);
        updateStatsPanel(stats);
        
        // 创建GeoJSON图层
        const earthquakeLayer = L.geoJSON(data, {
            pointToLayer: createEarthquakeMarker
        }).addTo(map);
        
        // 调整地图视图以适应所有标记
        if (data.features.length > 0) {
            map.fitBounds(earthquakeLayer.getBounds());
        }
        
        // 显示统计信息
        document.getElementById('earthquake-details').innerHTML = `
            <p>成功加载 ${data.features.length} 条地震数据 (最近24小时内)</p>
            <p>点击地图上的标记查看详细信息</p>
        `;
        
    } catch (error) {
        document.getElementById('earthquake-details').innerHTML = 
            `<div class="error">加载地震数据时出错: ${error.message}</div>`;
        console.error('Error fetching earthquake data:', error);
    }
}

// 初始化应用
function init() {
    // 创建粒子背景
    createParticles();
    
    // 添加图例
    addLegend();
    
    // 获取地震数据
    fetchEarthquakeData();
    
    // 每5分钟自动刷新数据
    setInterval(fetchEarthquakeData, 300000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);